package com.edg.realm;

import com.edg.dao.UserMapper;
import com.edg.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

public class UserRealm extends AuthorizingRealm {
    @Resource
    private UserMapper mapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取用户信息
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        //从数据库里设置角色
        Set<String> role = new HashSet<>();
        role.add(user.getRole());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(role);
        //从数据库里设置权限
        info.addStringPermission(user.getPerms());
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取token
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        //查找账号
        User user = mapper.selectByPrimaryKey(token.getUsername());
        if (user!=null){
            //Shiro验证密码
            return new SimpleAuthenticationInfo(user,user.getPwd(),getName());
        }
        return null;
    }
}
